package net.esj.basic.core.engine.schedule;

import java.lang.reflect.Method;
import java.util.NoSuchElementException;

import net.esj.basic.utils.UUIDCreator;

import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.support.ScheduledMethodRunnable;
import org.springframework.util.StringUtils;

public class Scheduler extends ScheduledMethodRunnable{
	
	public static final int SCHEDULE_TYPE_CRON = 1; 
	public static final int SCHEDULE_TYPE_TRIGGER = 2; 
	public static final int SCHEDULE_TYPE_FIXED_DELAY = 3; 
	public static final int SCHEDULE_TYPE_FIXED_RATE = 4; 

	protected String key;
	
	protected String cronAttribute;
	
	protected Long fixedDelayAttribute;
	
	protected Long fixedRateAttribute;
	
	protected Trigger trigger;

	public Scheduler( Object target, Method method) {
		super(target,method);
		this.key = UUIDCreator.create();
	}
	
	public Scheduler(Object target, String method) throws NoSuchMethodException{
		super(target,method);
		this.key = UUIDCreator.create();
	}
	
	public Scheduler(String key, Object target, Method method) {
		super(target,method);
		this.key = key;
	}
	
	public Scheduler(String key, Object target, String method) throws NoSuchMethodException{
		super(target,method);
		this.key = key;
	}
	
	public String getCronAttribute() {
		return cronAttribute;
	}

	public void setCronAttribute(String cronAttribute) {
		clearType();
		this.cronAttribute = cronAttribute;
	}

	public Long getFixedDelayAttribute() {
		return fixedDelayAttribute;
	}

	public void setFixedDelayAttribute(Long fixedDelayAttribute) {
		clearType();
		this.fixedDelayAttribute = fixedDelayAttribute;
	}

	public Long getFixedRateAttribute() {
		return fixedRateAttribute;
	}

	public void setFixedRateAttribute(Long fixedRateAttribute) {
		clearType();
		this.fixedRateAttribute = fixedRateAttribute;
	}

	public Trigger getTrigger() {
		return trigger;
	}

	public void setTrigger(Trigger trigger) {
		clearType();
		this.trigger = trigger;
	}
	
	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	/**
	 * 每个任务只有一种方式，set前必须清楚其他方式
	 */
	private void clearType(){
		this.cronAttribute  = null;
		this.fixedDelayAttribute = null;
		this.fixedRateAttribute = null;
		this.trigger = null;
	}
	
	public int resolveScheduleType(){
		if(StringUtils.hasText(cronAttribute)){
			return SCHEDULE_TYPE_CRON;
		}
		if(fixedDelayAttribute!=null && fixedDelayAttribute>0){
			return SCHEDULE_TYPE_FIXED_DELAY;
		}
		if(fixedRateAttribute!=null && fixedRateAttribute>0 ){
			return SCHEDULE_TYPE_FIXED_RATE;
		}
		if(trigger!=null){
			return SCHEDULE_TYPE_TRIGGER;
		}
		throw new NoSuchElementException("没有对应的任务类型!");
	}
}
